var ajaxMusicUpload=function(){
    var opts={
        ID:'#upload-music',
        uploadUrl:'/merse/music/upload',
        upExt:'mp3',
        uploadInputName:'music',
        data:{},
        autoSubmit:true,
        onSelect:null,
        onSubmit:null,
        onComplete:function(data){
            if (data.success) {
                saveResult(1,data.msg);
            } else {
                saveResult(0,data.msg);
            }
        },
        onProgress:null,
        onError:function(data){
            if(data.message){
                saveResult(0,data.message);
            }
            else{
                saveResult(0,"上传错误");
            }
        },
        multiple:false //多文件，只支持Html5
    };
    opts=$.extend({},opts,arguments[0]||{});
    var _this=this;
    var checkFileExt=function(filename,limitExt){
        if(limitExt==='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i'))){
            return true;
        }else{
            if(opts.onError!=null){
                opts.onError({
                    type:"ext",
                    message:"上传文件必需为: "+limitExt
                });
            }
            return false;
        }
    };
    this.uploadMusicAjax;
    var uploadInitMusic=function(){
        var $btn= typeof opts.ID == "object" ? opts.ID : $(opts.ID);
        var $file=$('<input type="file" class="upload-file" style="position:absolute;top:-30px;right:-10px;padding:0;margin:0;height:auto;font-size:460px;cursor: pointer; opacity: 0;" tabindex="-1" '+(opts.multiple?"multiple":"")+'/>');
        $file.css({
            opacity:0
        });
        $btn.css({
            position:'relative',
            overflow:'hidden',
            display:'inline-block'
        }).append($file);

        if(opts.onSelect!=null){
            $file.on("change",function(){
                opts.onSelect($file[0]);
            });
        }

        //开始上传
        _this.uploadMusicAjax=function(postdata){
            if(opts.onSubmit!=null&&!opts.onSubmit($file[0])){
                return false;
            }
            startUpload($file[0],postdata||{});
        };
        //自动上传
        if(opts.autoSubmit){
            $file.on("change",function(){
                if($file.val() != ''){
                    _this.uploadMusicAjax(opts.data);
                }
            });
        }
    };
    var startUpload=function(fromFiles,postdata){
        var onUploadCallback=function(sText,bFinish){
            var data={},bOK=false;
            try{
                data=eval("("+sText+")");
            }catch(ex){};
//                if(data.status==1){
            if(data){
                bOK=true;
            }
            if(bFinish&&bOK){

                if(opts.onComplete!=null)opts.onComplete(data);
            }//全部上传完成
            return bOK;
        }

        var upload,fileList;
        if(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])){
            if(!checkFileExt(fromFiles.value,opts.upExt))return;
            upload=new html4Upload(fromFiles,opts.uploadUrl,postdata,onUploadCallback);
        }else{
            if(!fileList)fileList=fromFiles;//文件列表
            var i,len=fileList.length;
            for(i=0;i<len;i++)if(!checkFileExt(fileList[i].name,opts.upExt))return;
            upload=new html5Upload(fileList,opts.uploadUrl,postdata,onUploadCallback,function(ev){
                if(opts.onProgress!=null)opts.onProgress(ev);
            });
        }
        upload.start();
    };
    var html4Upload=function(fromfile,toUrl,postdata,callback){
        var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
        var jIO=$('<iframe name="'+idIO+'" style="display:none"/>').appendTo('body');
        var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" style="display:none"></form>').appendTo('body');
        var jOldFile = $(fromfile).attr("name",opts.uploadInputName),jNewFile = jOldFile.clone().attr('disabled','true');
        jOldFile.before(jNewFile).appendTo(jForm);
        $.each(postdata,function(name,value){
            $('<input type="hidden" name='+name+' value='+value+' />').appendTo(jForm);
        })
        this.remove=function()
        {
            if(_this!==null)
            {
                jOldFile.removeAttr("name");
                jNewFile.before(jOldFile).remove();
                jIO.remove();
                jForm.remove();
                _this=null;
            }
        }
        this.onLoad=function(){
            var ifmDoc=jIO[0].contentWindow.document,result=$(ifmDoc.body).text();
            ifmDoc.write('');
            _this.remove();
            callback(result,true);
        }
        this.start=function(){
            jForm.submit();
            jIO.load(_this.onLoad);
        }
        return this;
    };
    var html5Upload=function(fromFiles,toUrl,postdata,callback,onProgress){
        var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
        for(var j=0;j<count;j++)allSize+=fromFiles[j].size;
        this.remove=function(){
            if(xhr){
                xhr.abort();
                xhr=null;
            }
        }
        this.uploadNext=function(sText){
            if(sText)//当前文件上传完成
            {
                allLoaded+=fromFiles[i-1].size;
                returnProgress(0);
            }
            if((!sText||(sText&&callback(sText,i===count)===true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){
                returnProgress(loaded);
            });
        }
        this.start=function(){
            _this.uploadNext();
        }
        function postFile(fromfile,toUrl,callback,onProgress){
            xhr = new XMLHttpRequest();
            var upload=xhr.upload;
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4)callback(xhr.responseText);
            };
            if(upload)upload.onprogress=function(ev){
                onProgress(ev.loaded);
            };
            else onProgress(-1);//不支持进度
            xhr.open("POST", toUrl,true);
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            var fd = new FormData();
            $.each(postdata,function(name,value){
                fd.append(name,value);
            })
            fd.append(opts.uploadInputName,fromfile);
            xhr.send(fd);
        }
        function returnProgress(loaded){
            if(onProgress)onProgress({
                'loaded':allLoaded+loaded,
                'total':allSize
            });
        }
    };
    uploadInitMusic();
}